package jnpf.property.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.base.UserInfo;
import jnpf.permission.model.authorize.AuthorizeConditionModel;
import jnpf.permission.service.AuthorizeService;
import jnpf.property.entity.ZcInspectionPlanEntity;
import jnpf.property.entity.ZcInspectionPlanVo;
import jnpf.property.mapper.ZcInspectionPlanMapper;
import jnpf.property.model.inspection.ZcInspectionPlanForm;
import jnpf.property.model.inspection.ZcInspectionPlanPagination;
import jnpf.property.service.ZcInspectionPlanService;
import jnpf.util.GeneraterSwapUtil;
import jnpf.util.ServletUtil;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import jnpf.zcasset.service.ZcAssetInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 巡检计划 Service Impl
 */
@Service
public class ZcInspectionPlanServiceImpl extends ServiceImpl<ZcInspectionPlanMapper, ZcInspectionPlanEntity> implements ZcInspectionPlanService {


    @Autowired
    private ZcAssetInfoService assetInfoService;

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private AuthorizeService authorizeService;

    @Override
    public boolean creatPlan(ZcInspectionPlanForm form) {
        ZcInspectionPlanEntity planEntity = BeanUtil.copyProperties(form, ZcInspectionPlanEntity.class);
        // 设置ID
        planEntity.setId(IdUtil.getSnowflake(1, 1).nextIdStr());
        // 设置空间
        planEntity.setSpace(CollUtil.join(form.getAssetList(),","));
        // 新建时,状态为未发布
        planEntity.setStatus(0);

        UserInfo userInfo = userProvider.get();
        planEntity.setCreatortime(DateUtil.date());
        planEntity.setCreatoruserid(userInfo.getUserId());

        return save(planEntity);
    }

    @Override
    public boolean updatePlan(ZcInspectionPlanForm form) {
        ZcInspectionPlanEntity planEntity = BeanUtil.copyProperties(form, ZcInspectionPlanEntity.class);

        // 设置空间
        planEntity.setSpace(CollUtil.join(form.getAssetList(),","));

        UserInfo userInfo = userProvider.get();
        planEntity.setLastmodifytime(DateUtil.date());
        planEntity.setLastmodifyuserid(userInfo.getUserId());

        return updateById(planEntity);
    }

    @Override
    public ZcInspectionPlanVo getPlanInfo(String id) {
        ZcInspectionPlanVo vo = BeanUtil.copyProperties(getById(id), ZcInspectionPlanVo.class);
        // 获取资产信息
        if (StrUtil.isNotEmpty(vo.getSpace())) {
            String[] assetIds = vo.getSpace().split(",");
            vo.setAssetList(assetInfoService.listByIds(Arrays.asList(assetIds)));

        }
        return vo;
    }

    @Override
    public List<ZcInspectionPlanEntity> getPlanList(ZcInspectionPlanPagination pagination) {

        QueryWrapper<ZcInspectionPlanEntity> planQueryWrapper = new QueryWrapper<>();

        boolean isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");

        if (isPc) {
            // 非管理员情况
            if (!userProvider.get().getIsAdministrator()) {
                // 没Menu权限返回空集
                Object planObj = authorizeService.getCondition(new AuthorizeConditionModel(planQueryWrapper, pagination.getMenuId(), "zcgl_inspection_plan"));
                if (ObjectUtil.isEmpty(planObj)) {
                    return new ArrayList<>();
                } else {
                    planQueryWrapper = (QueryWrapper<ZcInspectionPlanEntity>) planObj;
                }
            }

        }

        // 非PC处理
        if (!isPc) {

        }

        // 条件赋值
        if (StrUtil.isNotEmpty(pagination.getPlanName())) {
            planQueryWrapper.lambda().like(ZcInspectionPlanEntity::getPlanName, pagination.getPlanName());
        }

        if (CollUtil.isNotEmpty(pagination.getProjectId())) {
            planQueryWrapper.lambda().in(ZcInspectionPlanEntity::getProjectId, pagination.getProjectId());
        }

        if (pagination.getStatus() != null) {
            planQueryWrapper.lambda().eq(ZcInspectionPlanEntity::getStatus, pagination.getStatus());
        }


        //排序
        if (StringUtil.isEmpty(pagination.getSidx())) {
            planQueryWrapper.lambda().orderByDesc(ZcInspectionPlanEntity::getId);
        } else {
            try {
                // 获取排序列
                String sortFiled = pagination.getSidx();
                ZcInspectionPlanEntity obj = new ZcInspectionPlanEntity();
                Field declaredField = obj.getClass().getDeclaredField(sortFiled);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                planQueryWrapper = "asc".equals(pagination.getSort().toLowerCase()) ? planQueryWrapper.orderByAsc(value) : planQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }

        IPage<ZcInspectionPlanEntity> data = this.page(new Page<>(pagination.getCurrentPage(), pagination.getPageSize()), planQueryWrapper);
        return pagination.setData(data.getRecords(), data.getTotal());
    }


}
